<?php

namespace app\supplier\controller;

use app\erp\model\Baojiadb;
use app\erp\model\Goodsdb;
use app\erp\model\SiteConfigdb;
use think\Db;

class Baojia extends Base
{
    protected $cols = array(
        array(
            'field' => 'baojia_id',
            'width' => 50,
            'title' => 'ID',
            'fixed' => 'left',
            'hide' => 'true'
        ),
        array(
            'field' => 'create_time',
            'width' => 120,
            'title' => '报价时间'
        ),
        array(
            'field' => 'audit_time',
            'width' => 120,
            'title' => '审核时间'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称'
        ),
        array(
            'field' => 'goods_shuzi',
            'width' => 160,
            'title' => '数字编码'
        ),
        array(
            'field' => 'baojia',
            'width' => 120,
            'title' => '报价',
            //'edit' => false
        ),

        array(
            'field' => 'chengben',
            'width' => 120,
            'title' => '供应商成本价'
        ),
        array(
            'field' => 'cankao',
            'width' => 120,
            'title' => '参考价'
        ),

        array(
            'field' => 'audit_state',
            'width' => 120,
            'title' => '审核状态',
            'templet' => '#audit_stateTpl'
        ),
        array(
            'field' => 'zhouqi',
            'width' => 120,
            'title' => '报价期限'
        ),
        array(
            'field' => 'kucun',
            'width' => 120,
            'title' => '库存'
        ),

        array(
            'field' => 'zhenshi',
            'width' => 120,
            'title' => '真实库存',
            'edit' => true
        ),
        array(
            'field' => 'lilv',
            'width' => 120,
            'title' => '报价利润率'
        ),
        array(
            'field' => 'beizhu',
            'width' => 160,
            'title' => '供应商业务员'
        ),
        array(
            'field' => 'remark',
            'width' => 160,
            'title' => '拒绝原因'
        ),
        array(
            'field' => 'audit_member_id',
            'width' => 120,
            'title' => '审核人',
            'templet' => '#audit_member_idTpl'
        ),
        array(
            'field' => 'beizhu2',
            'width' => 120,
            'title' => '运营备注2'
        ),
        array(
            'field' => 'goods_type',
            'width' => 120,
            'title' => '产品类型'
        ),
        array(
            'field' => 'apply_member_id',
            'width' => 120,
            'title' => '供应商',
            'templet' => '#apply_member_idTpl'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 160,
            'title' => '字母编码'
        ),
        array(
            'field' => 'apply_member_id',
            'width' => 120,
            'title' => '报价人',
            'templet' => '#apply_member_idTpl',
            'hide' => 'true'
        ),

        array(
            'field' => 'beizhu1',
            'width' => 160,
            'title' => '运营备注1',
            'hide' => 'true'
        )

    );
    public $param = array();

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->param = $param;
    }

    public function index()
    {
        $this->assign('cols', json_encode($this->cols));
        return $this->fetch();
    }

    // 批量同步真实库存
    public function updatezhenshi()
    {
        $configdb = new SiteConfigdb();
        $configdb->param['config_name'] = 'UP_ALL_AREA';
        $true_supplier_id = $configdb->getValue();
        $true_supplier_arr = explode(',', $true_supplier_id);
        $is_admins = in_array(MEMBER_ID, $true_supplier_arr);
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        try {
            foreach ($files as $file) {
                $info = $file->validate([
                    'site' => 1024 * 10 * 1024 * 1024,
                    'ext' => 'xls,xlsx'
                ])->move('./uploads/');
                if ($info) {
                    $fileName = './uploads/' . $info->getSaveName();
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objReader->setReadDataOnly(true);
                    $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                    $sheet = $objPHPExcel->getSheet();
                    $get_row_num = $sheet->getHighestRow(); // 总行数
                    $data = array();
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    $baojiadb = new Baojiadb();
                    $goodsdb = new Goodsdb();
                    $data = [];
                    Db::startTrans();
                    $error_flag = 1;
                    $temp['state'] = 1;
                    $temp['msg'] = '成功';
                    $error_msg = '';
                    for ($i = 2; $i <= $get_row_num; $i++) {
                        $temp['goods_sku'] = $this->getSheetValue($the_sheet, "A" . $i);
                        $temp['zhenshi'] = intval($this->getSheetValue($the_sheet, 'B' . $i));
                        $diqu = $this->getSheetValue($the_sheet, "C" . $i);
                        $temp['shengfen'] = $this->getSheetValue($the_sheet, 'D' . $i);

                        if ($temp['zhenshi'] < 1) {
                            $error_flag = 0;
                            $temp['state'] = 0;
                            $temp['msg'] = $temp['goods_sku'].'真实库存为0';
                            $error_msg = $temp['msg'];
                        }

                        // 开始校验
                        $get_goods = $goodsdb->where('jun_id', $temp['goods_sku'])->where('callet_juncai',1)->find();
                        if ($diqu == '') {
                            $diqu_id = $get_goods['diqu'];
                            $temp['shengfen'] = $get_goods['shengfen'];
                        } else {
                            $diqu_id = '0';
                            if ($diqu == '非偏远地区') {
                                $diqu_id = '1';
                            }
                            if ($diqu == '偏远地区') {
                                $diqu_id = '2';
                            }
                        }

                        if ($get_goods) {
                            $get_baojia = $baojiadb->where('goods_sku', $get_goods['goods_sku'])->order('baojia_id', 'desc')->find();

                            /*if ($get_baojia['active'] != true) {
                                $temp['state'] = 0;
                                $temp['msg'] = '报价等待审核';
                                $error_flag = 0;
                                $error_msg = $temp['msg'];
                            }*/
                            if ($get_baojia) {
                                if ($is_admins || $get_baojia['apply_member_id'] == MEMBER_ID) {
                                    $get_baojia->save(['zhenshi' => $temp['zhenshi'], 'shengfen' => $temp['shengfen'], 'diqu_id' => $diqu_id]);
                                    $get_goods->save(['zhenshi' => $temp['zhenshi'], 'shengfen' => $temp['shengfen'], 'diqu_id' => $diqu_id]);
                                    $temp['msg'] = '修改成功';
                                    $temp['state'] = 1;
                                } else {
                                    $error_flag = 0;
                                    $temp['msg'] = $temp['goods_sku'].'没权限修改其他供应商报价商品';
                                    $temp['state'] = 0;
                                    $error_msg = $temp['msg'];
                                }
                            } else {
                                $error_flag = 0;
                                $temp['state'] = 0;
                                $temp['msg'] = $temp['goods_sku'].'尚未报价';
                                $error_msg = $temp['msg'];
                            }
                            array_push($data, $temp);
                        } else {
                            $error_flag = 0;
                            $temp['state'] = 0;
                            $temp['msg'] = $temp['goods_sku'].'未找到商品';
                            $error_msg = $temp['msg'];
                            array_push($data, $temp);
                        }
                    }
                    if ($error_flag == 0) {
                        Db::rollback();
                        $this->layuiReturn($error_msg, 0, '错误:' . $error_msg, 0);
                    } else {
                        Db::commit();
                        $this->layuiReturn($data, 0, '导入成功', 1);

                    }

                } else {
                    Db::rollback();
                    $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
                }
            }
        } catch (\Exception $e) {
            $this->layuiReturn('excel格式错误' . $e->getMessage(), 0, 'excel格式错误', 0);
        }

    }

    // 修改真实库存
    public function edit()
    {
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->find($this->param['baojia_id']);
        if ($get_baojia) {
            $get_baojia->save(['zhenshi' => $this->param['value']]);
            $goodsdb = new Goodsdb();
            $get_goods = $goodsdb->where('goods_id', $get_baojia['goods_id'])->find();
            if ($get_goods) {
                $get_goods->save(['zhenshi' => $this->param['value']]);
            }
        }
        $this->success('报价成功');
    }

    public function ajaxList()
    {
        $baojiadb = new Baojiadb();
        $baojiadb->param = $this->param;
        $baojiadb->param['apply_member_id'] = MEMBER_ID;
        $get_baojia_count = $baojiadb->count();
        $get_baojia = $baojiadb->with(['users', 'admins'])->order('baojia_id desc')->page($this->param['page'], $this->param['limit'])->select();
        $this->layuiReturn($get_baojia, $get_baojia_count);
    }

    public function export()
    {
        $baojiadb = new Baojiadb();
        $baojiadb->param = $this->param;
        $get_baojia = $baojiadb->with(['users', 'admins'])->order('baojia_id desc')->select();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '报价商品' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '产品类型',
            '供应商',
            '报价时间',
            '字母编码',
            '数字编码',
            '商品名称',
            '利润率',
            '审核时间',
            '供应商成本价',
            '参考价',
            '报价',
            '库存',
            // '厂家成本',
            '审核状态',
            '拒绝原因',
            '审核人',
            //  '运营备注1',
            '运营备注2',
            '报价期限',
            '供应商业务员'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $audit_state_arr = array(
            '1' => '审核通过',
            '2' => '等待审核',
            '3' => '驳回审核'
        );
        foreach ($get_baojia as $key => $val) {
            unset ($temp);
            $temp [0] = $val ['goods_type'];
            $temp [1] = $val ['users']['supplier_name'];
            $temp [2] = $val ['create_time'];
            $temp [3] = $val ['goods_sku'];
            $temp [4] = $val ['goods_shuzi'];
            $temp [5] = $val ['goods_name'];
            $temp [6] = $val ['lilv'];
            $temp [7] = $val ['audit_time'];
            $temp [8] = $val ['chengben'];
            $temp [9] = $val ['cankao'];
            $temp [10] = $val ['baojia'];
            $temp [11] = $val ['kucun'];
            //   $temp [11] = $val ['caigoujia'];
            $temp [12] = $audit_state_arr[$val ['audit_state']];
            $temp [13] = $val ['remark'];
            $temp [14] = $val ['admins']['realname'];
            //  $temp [16] = $val ['beizhu1'];
            $temp [15] = $val ['beizhu2'];
            $temp [16] = $val['zhouqi'];
            $temp [17] = $val['beizhu'];

            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        if ($ceil_num > 1) {
            for ($y = 0; $y < 33; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

}